package org.ftz.control;
import javax.sound.sampled.*;
import javax.sound.sampled.DataLine.Info;
public class AudioUtils {
    private static AudioFormat af;
    private static Info info;
    private static TargetDataLine td;
    private static Info dataLineInfo;
    private static SourceDataLine sd;
    public static TargetDataLine getTargetDataLine() throws LineUnavailableException { //获取音频流数据(从拾音器)
        if (td != null) {
            return td;
        } else {
                af = getAudioFormat();  // 1.获取音频流数据
                info = new Info(TargetDataLine.class, af);
                td = (TargetDataLine) (AudioSystem.getLine(info));
                td.open(af); // 打开具有指定格式的行，这样可使行获得所有所需的系统资源并变得可操作。
                td.start(); // 允许某一数据行执行数据 I/O
            return td;
        }
    }
    public static SourceDataLine getSourceDataLine() throws LineUnavailableException { //获取混编器 写入数据会自动播放
        if (sd != null) {
            return sd;
        } else {
                dataLineInfo = new Info(SourceDataLine.class, af); // 2.从音频流获取数据
                sd = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
                sd.open(af);
                sd.start();
            return sd;
        }
    }
    public static AudioFormat getAudioFormat() { //设置AudioFormat的参数
        AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
        float rate = 8000f;
        int sampleSize = 16;
        String signedString = "signed";
        boolean bigEndian = true;
        int channels = 1;
        return new AudioFormat
                (encoding, rate, sampleSize, channels, (sampleSize / 8) * channels, rate, bigEndian);
    }
    public static void close() { //关闭资源
        if (td != null) {
            td.close();
        }
        if (sd != null) {
            sd.close();
        }
    }
}
